var grid_selector = "#grid-table";
var pager_selector = "#grid-pager";
var columnsMap = new Map();//创建map，存储栏目信息

jQuery(function($) {
	
	var parent_column = $(grid_selector).closest('[class*="col-"]');
	//resize to fit page size
	$(window).on('resize.jqGrid', function () {
		$(grid_selector).jqGrid( 'setGridWidth', parent_column.width() );
    })
	
	//resize on sidebar collapse/expand
	$(document).on('settings.ace.jqGrid' , function(ev, event_name, collapsed) {
		if( event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed' ) {
			//setTimeout is for webkit only to give time for DOM changes and then redraw!!!
			setTimeout(function() {
				$(grid_selector).jqGrid( 'setGridWidth', parent_column.width() );
			}, 20);
		}
    })
	
	jQuery(grid_selector).jqGrid({
		subGrid : false,//是否开启子菜单
		data: getContentData(),
		datatype: "local",
		//height: 375,
		height: '100%',
		colNames:['ID', '栏目', '标题', '副标题', '标题图片', '链接', '描述'],
		colModel:[
			{name:'id',index:'id', sorttype:"int", editable: true, hidden: true},
			{name:'columnId',index:'columnId', editable:true, edittype:'select', editoptions:{value: getColumns()}, formatter:getColumnName},
			{name:'title',index:'title', editable: true, editrules:{required:true}},
			{name:'subTitle',index:'subTitle', editable: true},
			{name:'img',index:'img', align:'center', editable: false, search:false, formatter:showImg},
			{name:'links',index:'links', editable: true},
			{name:'description',index:'description', editable: true,edittype:"textarea"}
		],
		viewrecords : true,
		rowNum:10,
		rowList:[10,20,30],
		pager : pager_selector,
		altRows: true,
		multiselect: true,
        multiboxonly: true,
		loadComplete : function() {
			var table = this;
			setTimeout(function(){
				styleCheckbox(table);
				
				updateActionIcons(table);
				updatePagerIcons(table);
				enableTooltips(table);
			}, 0);
		},
		editurl: "/admin/web/content/operation",//编辑保存发送的路径
//		caption: "文章列表",			
		autowidth: true
	});

	/**
	 * 显示图片信息
	 */
	function showImg(cellvalue, options, rowObject){
		return "<a onclick='openUploadModal(\"" + rowObject.id + "\")' style='cursor:pointer;' title='点击修改图片'><img src='" +cellvalue  + "' height='50' /></a>";
	}
	
	/**
	 * 获取栏目信息列表，返回为select中可用的节点
	 */
	function getColumns(){
		var str = "";
		columnsMap.clear();
		$.ajax({
			url: '/admin/web/columns/ajaxColumnsList',
			type: 'POST',
			dataType: 'json',
			async: false,
			success: function(obj){
				if(obj != null){
					for(var i = 0; i < obj.data.length; i++){
						var id = obj.data[i].id;
						var name = obj.data[i].name;
						if(i != (obj.data.length - 1)){
							str += id + ":" + name + ";";
						}else{
							str += id + ":" + name;
						}
						columnsMap.put(id, name);
					}
				}
			}
		});
		return str;
	}

	/**
	 * 通过栏目id获取栏目名称
	 */
	function getColumnName(cellValue){
		return columnsMap.get(cellValue);
	}
	
	/**
	 * 显示操作后的回调信息，并且重新刷新表格
	 */
	function showOperInfo(xhr){
		if(xhr.responseJSON){
			if(xhr.responseJSON.status == 200){
				gritterSuccess(xhr.responseJSON.data);
			}else{
				gritterError(xhr.responseJSON.data);
			}
		}else{
			gritterError(info.noAuth);
		}
        
        $(grid_selector).jqGrid('clearGridData');
        $(grid_selector).jqGrid('setGridParam', {
        	data: getContentData(),//重新加载数据
        }).trigger('reloadGrid');//刷新表格
	}
	
	//trigger window resize to make the grid get the correct size
	$(window).triggerHandler('resize.jqGrid');

	//switch element when editing inline
	function aceSwitch( cellvalue, options, cell ) {
		setTimeout(function(){
			$(cell) .find('input[type=checkbox]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
		}, 0);
	}
	//enable datepicker
	function pickDate( cellvalue, options, cell ) {
		setTimeout(function(){
			$(cell).find('input[type=text]').datepicker({format:'yyyy-mm-dd' , autoclose:true}); 
		}, 0);
	}

	/**
	 * 下方导航栏按钮
	 */
	jQuery(grid_selector).jqGrid('navGrid',pager_selector,
		{ 	//导航选项
			edit: true,
			editicon : 'ace-icon fa fa-pencil blue',
			add: true,
			addicon : 'ace-icon fa fa-plus-circle purple',
			del: true,
			delicon : 'ace-icon fa fa-trash-o red',
			search: true,
			searchicon : 'ace-icon fa fa-search orange',
			refresh: true,
			refreshicon : 'ace-icon fa fa-refresh green',
			view: true,
			viewicon : 'ace-icon fa fa-search-plus grey',
		},
		{
			//编辑（修改）
			closeAfterEdit: true,
			//width: 700,
			recreateForm: true,
			beforeShowForm : function(e) {
				var form = $(e[0]);
				form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
				style_edit_form(form);
			},
//			afterSubmit: function(response, postdata){
//				upload(postdata.id);
//				showOperInfo(response);
//				window.location.reload();
//			}
//			,
			afterComplete: function(xhr){
				showOperInfo(xhr);
			}
		},
		{
			//添加
			//width: 700,
			closeAfterAdd: true,
			recreateForm: true,
			viewPagerButtons: false,
			beforeShowForm : function(e) {
				var form = $(e[0]);
				form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
				style_edit_form(form);
			},
//			afterSubmit: function(response, postdata){
//				upload(postdata.id);
//				showOperInfo(response);
//				window.location.reload();
//			}
//			,
			afterComplete: function(xhr){
				showOperInfo(xhr);
			}			
		},
		{
			//删除
			recreateForm: true,
			beforeShowForm : function(e) {
				var form = $(e[0]);
				if(form.data('styled')) return false;
				
				form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
				style_delete_form(form);
				
				form.data('styled', true);
			},
			onClick : function(e) {

			},
			afterComplete:function(xhr){//删除之后的回调
				showOperInfo(xhr);
		    }
		},
		{
			//搜索
			recreateForm: true,
			afterShowSearch: function(e){
				var form = $(e[0]);
				form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
				style_search_form(form);
			},
			afterRedraw: function(){
				style_search_filters($(this));
			},
			multipleSearch: true,
			/**
			multipleGroup:true,
			showQuery: true
			*/
		},
		{
			//查看所选记录
			recreateForm: true,
			beforeShowForm: function(e){
				var form = $(e[0]);
				form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
			}
		}
	)
	
	function style_edit_form(form) {
		//enable datepicker on "sdate" field and switches for "stock" field
		form.find('input[name=sdate]').datepicker({format:'yyyy-mm-dd' , autoclose:true})
		
		form.find('input[name=stock]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
				   //don't wrap inside a label element, the checkbox value won't be submitted (POST'ed)
				  //.addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');
		
		//update buttons classes
		var buttons = form.next().find('.EditButton .fm-button');
		buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
		buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
		buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')
		
		buttons = form.next().find('.navButton a');
		buttons.find('.ui-icon').hide();
		buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
		buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');	
	}

	function style_delete_form(form) {
		var buttons = form.next().find('.EditButton .fm-button');
		buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-icon
		buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
		buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>')
	}
	
	function style_search_filters(form) {
		form.find('.delete-rule').val('X');
		form.find('.add-rule').addClass('btn btn-xs btn-primary');
		form.find('.add-group').addClass('btn btn-xs btn-success');
		form.find('.delete-group').addClass('btn btn-xs btn-danger');
	}
	function style_search_form(form) {
		var dialog = form.closest('.ui-jqdialog');
		var buttons = dialog.find('.EditTable')
		buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
		buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
		buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
	}
	
	function beforeDeleteCallback(e) {
		var form = $(e[0]);
		if(form.data('styled')) return false;
		
		form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
		style_delete_form(form);
		
		form.data('styled', true);
	}
	
	function beforeEditCallback(e) {
		var form = $(e[0]);
		form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
		style_edit_form(form);
	}

	//复选框样式
	function styleCheckbox(table) {

	}
	
	//unlike navButtons icons, action icons in rows seem to be hard-coded
	//you can change them like this in here if you want
	function updateActionIcons(table) {

	}
	
	//replace icons with FontAwesome icons like above
	function updatePagerIcons(table) {
		var replacement = 
		{
			'ui-icon-seek-first' : 'ace-icon fa fa-angle-double-left bigger-140',
			'ui-icon-seek-prev' : 'ace-icon fa fa-angle-left bigger-140',
			'ui-icon-seek-next' : 'ace-icon fa fa-angle-right bigger-140',
			'ui-icon-seek-end' : 'ace-icon fa fa-angle-double-right bigger-140'
		};
		$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
			var icon = $(this);
			var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
			
			if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
		})
	}

	function enableTooltips(table) {
		$('.navtable .ui-pg-button').tooltip({container:'body'});
		$(table).find('.ui-pg-div').tooltip({container:'body'});
	}

	//var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');

	$(document).one('ajaxloadstart.page', function(e) {
		$.jgrid.gridDestroy(grid_selector);
		$('.ui-jqdialog').remove();
	});

	/**
	 * 图片上传窗口
	 */
	$('#input-file-img').ace_file_input({
		style: 'well',
		btn_choose: '点击或将图片拖动到此处进行上传',
		btn_change: null,
		no_icon: 'ace-icon fa fa-picture-o',
		droppable: true,
		thumbnail: 'large',//large | fit | small
		allowExt: ["jpeg", "jpg", "png", "gif" , "bmp"],
		allowMime: ["image/jpg", "image/jpeg", "image/png", "image/gif", "image/bmp"],
		preview_error : function(filename, error_code) {
			
		}	
	}).on('change', function(){
		
	});

});

/**
 * 异步加载数据列表
 */
function getContentData(){
	var data = [];
	var url = '/admin/web/content/ajaxContentList';
	$.ajaxSettings.async = false;
	$.getJSON(url,'',function(result, e){
		if(result.error){
			
        }else{
            data = result.data;
        }
	});
	return data;
}

/**
 * 打开图片上传模态框
 * @param obj
 * @returns
 */
var uploadContentId;
function openUploadModal(id){
	uploadContentId = id;
	$('#uploadImgModal').modal('show');
}

/**
 * 图片上传
 * @returns
 */
$('#form-img-btn').on('click', function(){
	var formData = new FormData();
	var file = document.getElementById('input-file-img').files[0];
	if(file != null){
		formData.append('file', file);
		upload('/admin/web/content/uploadImg?id=' + uploadContentId, formData);
		$('.ace-file-input').find('a[class="remove"]').trigger('click');//清除文件上传框中的内容
	}else {
		return false;
	}
})

/**
 * 异步请求上传文件
 * @param url
 * @param data
 * @returns
 */
function upload(url, data){
	$.ajax({
		url: url,
		data: data,
		method: 'post',
		dataType: 'json',
		async: false,
		contentType:false,
		processData:false,
		success: function(obj){
			if(obj.status == 200){
				gritterSuccess(obj.data);
		        
		        $(grid_selector).jqGrid('clearGridData');
		        $(grid_selector).jqGrid('setGridParam', {
		        	data: getContentData(),//重新加载数据
		        }).trigger('reloadGrid');//刷新表格
				$('#uploadImgModal').modal('hide');
				//window.location.reload();
			}else{
				gritterError(obj.msg);
			}
		},
		error: function(obj){
			gritterError('您无权操作此项');
		}
	});
}

